﻿using Azure;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using english_sentences.Services.Interface;

namespace english_sentences.Services
{
    public class BlobService : IBlobService
    {
        private readonly IConfiguration _configuration;

        private readonly string FileURI;

        private BlobServiceClient _blobServiceClient;

        public BlobService(IConfiguration configuration)
        {
            this._configuration = configuration;
            // Retrieve the connection string for use with the application. 
            string connectionString = _configuration.GetSection("AZURE_STORAGE_CONNECTION_STRING").Value;
            // Create a BlobServiceClient object 
            this._blobServiceClient = new BlobServiceClient(connectionString);

            this.FileURI = $"{_configuration.GetSection("STORAGE_URI").Value}/{_configuration.GetSection("CONTAINER_NAME").Value}";
        }

        public async Task<string> SaveFile(byte[] bytes)
        {
            if (this._blobServiceClient == null) throw new Exception("blob client failed to init.");

            var fileName = Guid.NewGuid().ToString() + ".mp3";

            BlobContainerClient containerClient =
                this._blobServiceClient.GetBlobContainerClient(_configuration.GetSection("CONTAINER_NAME").Value);

            BlobClient blobClient = containerClient.GetBlobClient(fileName);

            // await blobClient.SetHttpHeadersAsync(new BlobHttpHeaders { CacheControl = "public,max-age=604800" });

            await blobClient.UploadAsync(new BinaryData(bytes), new BlobUploadOptions { HttpHeaders = new BlobHttpHeaders { CacheControl = "public,max-age=604800" } });

            return $"{this.FileURI}/{fileName}";

        }

    }
}
